/*
 * @lc app=leetcode.cn id=1670 lang=javascript
 *
 * [1670] 设计前中后队列
 */

// @lc code=start


/**
 * 思路：用两个双端队列来实现
 * 借用了数组的api, 应该自己封装双端队列。
 */

var FrontMiddleBackQueue = function () {
  this.leftQueue = new Array();
  this.rightQueue = new Array(); // 奇数时右侧数组大1
  this.count = 0;
};

// 调节两个对列的元素
FrontMiddleBackQueue.prototype.ava = function () {
  // 右侧个数比左侧多，且多于1个
  while (this.rightQueue.length - this.leftQueue.length > 1) {
    this.leftQueue.push(this.rightQueue.shift())
  }
  // 左侧比右侧多
  while (this.rightQueue.length - this.leftQueue.length < 0) {
    this.rightQueue.unshift(this.leftQueue.pop())
  }
};

FrontMiddleBackQueue.prototype.isEmpty = function () {
  return this.count === 0;
};

FrontMiddleBackQueue.prototype.pushFront = function (val) {
  this.leftQueue.unshift(val);
  this.count++;
  this.ava();
  return null;
};

FrontMiddleBackQueue.prototype.pushMiddle = function (val) {
  this.leftQueue.push(val);
  this.count++;
  this.ava();
  return null;
};

FrontMiddleBackQueue.prototype.pushBack = function (val) {
  this.rightQueue.push(val);
  this.count++;
  this.ava();
  return null;
};

FrontMiddleBackQueue.prototype.popFront = function () {
  if (this.isEmpty()) return -1;
  let value = ''
  // 优先弹出左侧队列的元素
  if (this.leftQueue.length) {
    value = this.leftQueue.shift();
  } else {
    value = this.rightQueue.shift();
  }
  this.count--;
  this.ava();
  return value;
};

FrontMiddleBackQueue.prototype.popMiddle = function () {
  if (this.isEmpty()) return -1;
  let value = ''
  // 如果是偶数个，弹出中间偏左的元素
  if (this.rightQueue.length === this.leftQueue.length) {
    value = this.leftQueue.pop();
  } else { // 否则中间元素为右队列第一个
    value = this.rightQueue.shift();
  }
  this.count--;
  this.ava();
  return value;
};

FrontMiddleBackQueue.prototype.popBack = function () {
  if (this.isEmpty()) return -1;
  let value = this.rightQueue.pop();  // 右侧的元素不会比左侧的少
  this.count--;
  this.ava();
  return value;
};

/**
 * Your FrontMiddleBackQueue object will be instantiated and called as such:
 * var obj = new FrontMiddleBackQueue()
 * obj.pushFront(val)
 * obj.pushMiddle(val)
 * obj.pushBack(val)
 * var param_4 = obj.popFront()
 * var param_5 = obj.popMiddle()
 * var param_6 = obj.popBack()
 */
// @lc code=end

